package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description WeChatServiceImpl
 * @Author songyu
 * @Date 2024-10-20
 */
@Service
public class WeChatServiceImpl implements WeChatService {


    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;

    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //1.封装3个请求参数Map<String,Object>
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("appid",appId);
        paramsMap.put("secret",secret);
        paramsMap.put("js_code",code);

        //2.远程调用返回json字符串
        String json = HttpUtil.post(REQUEST_URL, paramsMap);

        //3.将json字符串转换为JsonObject对象（就是map）
        JSONObject jsonObject = JSONUtil.parseObj(json);

        //4.判断是否发生错误，如果有错误抛出异常
        if(jsonObject.get("errcode")!=null){
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }

        //5.没有错误，返回openid
        return jsonObject.get("openid").toString();
    }

    /**
     * 获取手机号
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        //1.封装3个请求参数Map<String,Object>
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("code",phoneCode);

        //获取access_token
        String accessToken = getAccessToken();

        //2.远程调用返回json字符串
        String json = HttpUtil.post(PHONE_REQUEST_URL+accessToken, JSONUtil.toJsonStr(paramsMap));

        //3.将json字符串转换为JsonObject对象（就是map）
        JSONObject jsonObject = JSONUtil.parseObj(json);

        //4.判断是否发生错误，如果有错误抛出异常
        if(jsonObject.get("errcode")!=null && !jsonObject.getInt("errcode").equals(0)){
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }

        //5.没有错误，返回openid
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     * 获取手机号的令牌
     * @return
     */
    private String getAccessToken(){
        //1.封装2个请求参数Map<String,Object>
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("appid",appId);
        paramsMap.put("secret",secret);

        //2.远程调用返回json字符串
        String json = HttpUtil.get(TOKEN_URL, paramsMap);

        //3.将json字符串转换为JsonObject对象（就是map）
        JSONObject jsonObject = JSONUtil.parseObj(json);

        //4.判断是否发生错误，如果有错误抛出异常
        if(jsonObject.get("errcode")!=null){
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }

        //5.没有错误，返回openid
        return jsonObject.get("access_token").toString();
    }
}
